import Flutter
import UIKit
import YYModel

public class SwiftSimilarImgPlugin: NSObject, FlutterPlugin {
  
  private static var map: [String: Any] = [:]
    
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "similar_img", binaryMessenger: registrar.messenger())
    let instance = SwiftSimilarImgPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
      switch call.method {
      case "fectchSimilarArray":
          SwiftSimilarImgPlugin.map["fectchSimilarArray"] = result
          DispatchQueue.global().async {
              let dataArray = AMPhotoManager.fectchSimilarArray()
              var tmpArr:[[Any]] = []
              dataArray.forEach { item in
                  var tmpArrSub:[Any] = []
                  let tmp = item as! Array<PHAsset>
                  tmp.forEach { phAsset in
                      let entity = PMAssetEntity.convertPHAsset(toAssetEntity: phAsset, needTitle: false)
                      tmpArrSub.append(entity.yy_modelToJSONObject()!)
                  }
                  tmpArr.append(tmpArrSub)
              }
              (SwiftSimilarImgPlugin.map["fectchSimilarArray"] as! FlutterResult)(tmpArr)
          }
          break
      case "getThumb":
          SwiftSimilarImgPlugin.map["getThumb"] = result
          let arg = call.arguments as! [String : Any]
          let id = arg["id"] as! String
          let optionDict = arg["option"] as! [String : Any]
          let option = PMThumbLoadOption.init(dict: optionDict)
          PMAssetEntity.getThumbWithId(id, option: option) { data in
              (SwiftSimilarImgPlugin.map["getThumb"] as! FlutterResult)(data)
          }
          break
      case "getOrigin":
          SwiftSimilarImgPlugin.map["getOrigin"] = result
          let id = call.arguments as! String
          PMAssetEntity.getOriginImage(withId: id) { path in
              (SwiftSimilarImgPlugin.map["getOrigin"] as! FlutterResult)(path)
          }
          break
      case "removeAsset":
          SwiftSimilarImgPlugin.map["removeAsset"] = result
          let arg = call.arguments as! [String : Any]
          let id = arg["id"] as! String
          let type = arg["type"] as! Int32
          PMAssetEntity.removeAsset(withId: id, type: type) { boo in
              (SwiftSimilarImgPlugin.map["removeAsset"] as! FlutterResult)(boo)
          }
          break
      default:
          result("iOS " + UIDevice.current.systemVersion)
      }
  }
}
